<template>
  <div id="custom-table">
    <table>
      <thead>
      <tr>
        <th v-for="item in columns" @click="onSort(item.field, -sort_direction)">
          <span>{{ item.title }}</span>
          <span v-if="order_by === item.field" style="color: #409EFF;">{{ sort_direction === 1 ? "↑" : "↓" }}</span>
        </th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(row, index) in records">
        <td v-for="item in columns" :style="{ backgroundColor: getBackgroundColor(index) }"
            @click="onClick(row, item.field, index)">
          <div v-html="item.renderCell(row)"/>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  props: {
    columns: {
      type: Array,
      default: []
    },
    records: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      order_by: null,
      sort_direction: 1,
      index: null
    }
  },
  methods: {
    getBackgroundColor(index) {
      if (this.index === index) {
        return "#C2E5FA"
      } else {
        return index % 2 ? "#EEEEEE" : "#FFFFFF"
      }
    },
    onClick(row, field, index) {
      this.index = index
      this.$emit("onClick", row, field)
    },
    onSort(order_by, sort_direction) {
      this.order_by = order_by
      this.sort_direction = sort_direction
      this.$emit("onSort", order_by, sort_direction)
    }
  }
}
</script>

<style scoped>
#custom-table {
  width: 100%;
  text-align: center;
  overflow: scroll;
}

table {
  font-size: 14px;
  table-layout: fixed;
  line-height: 40px;
}

thead tr th {
  min-width: 74px;
  background-color: #fff;
  position: sticky;
  top: 0;
}

tbody tr td {
  min-width: 74px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

td:first-child {
  position: sticky;
  left: 0;
  z-index: 1;
}

th:first-child {
  position: sticky;
  left: 0;
  z-index: 2;
  background-color: #fff;
}
</style>
